package com.gulangyu.manage.mvc;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
import com.mycompany.yourtrade.common.DerongVariables;
import com.mycompany.yourtrade.common.RedisService;
import com.mycompany.yourtrade.common.SmsClient;
import com.mycompany.yourtrade.common.UpYunService;
import com.mycompany.yourtrade.model.AjaxResponse;
import com.mycompany.yourtrade.model.Area;
import com.mycompany.yourtrade.model.Category;
import com.mycompany.yourtrade.model.City;
import com.mycompany.yourtrade.model.LoginUser;
import com.mycompany.yourtrade.model.Province;
import com.mycompany.yourtrade.model.Seller;
import com.mycompany.yourtrade.model.Shop;
import com.mycompany.yourtrade.service.manage.ShopManageService;
import com.mycompany.yourtrade.service.user.UserService;
import com.qunshang.common.SellerSession;
import com.qunshang.common.SessionUtils;
import java.awt.Color;
import java.awt.Font;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import nl.captcha.Captcha;
import nl.captcha.text.producer.DefaultTextProducer;
import nl.captcha.text.renderer.DefaultWordRenderer;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
@RequestMapping("/")
public class HomeController {
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private UpYunService UpYunService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShopManageService shopManageService;
    @Autowired
    private SmsClient smaClient;
    @Autowired
    private RedisService redisService;
    @Autowired
    private DerongVariables derongVariables;
    
    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView login(ModelMap model) {
        ModelAndView mv = new ModelAndView("login");
        return mv;
    }
    
    @RequestMapping(value = "checklogin", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse checklogin(HttpServletRequest request, HttpServletResponse response,
            @Valid LoginUser model,
            BindingResult result,
            String imageCaptcha) {
        try {
            if (!SessionUtils.validateCaptcha(request, imageCaptcha)) {
                return new AjaxResponse(false, "图片验证码不正确");
            }
            if (!result.hasErrors()) {
                Seller sell = shopManageService.getSellerByMobile(model.getMobile());
                if (sell != null) {
                    if (BCrypt.checkpw(model.getPassword(), sell.getPassword())) {
                        Shop shop = shopManageService.getShopBySellerId(sell.getId());
                        // 创建商户Session
                        SellerSession session = new SellerSession(sell);
                        SessionUtils.setSession(request, session);
                        return new AjaxResponse(true, "", sell);
                    }
                }
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误");
    }
    
    @RequestMapping(value = "quicklogin", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse quicklogin(HttpServletRequest request, HttpServletResponse response, String mobile,
            String imageCaptcha, String checkcode) {
        try {
            if (!SessionUtils.validateCaptcha(request, imageCaptcha)) {
                return new AjaxResponse(false, "图片验证码不正确");
            }
            String sessionId = request.getSession().getId();
            String redis = redisService.getValueOps().get(sessionId);
            if (redis == null) {
                return new AjaxResponse(false, "手机验证码已失效，请重新发送验证码");
            } else {
                if (!checkcode.equals(redis)) {
                    return new AjaxResponse(false, "手机验证码不正确");
                } else {
                    Seller sell = shopManageService.getSellerByMobile(mobile);
                    if (sell == null) {
                        return new AjaxResponse(false, "您还未注册，请先注册");
                    } else {
                        Shop shop = shopManageService.getShopBySellerId(sell.getId());
                        // 创建商户Session
                        SellerSession session = new SellerSession(sell);
                        SessionUtils.setSession(request, session);
                        return new AjaxResponse(true, "", shop);
                    }
                }
            }
            
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误");
    }
    
    @RequestMapping(value = "sendSms", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse sendSms(HttpServletRequest request, HttpServletResponse response, String mobile, String imageCaptcha) {
        try {
            String sessionId = request.getSession().getId();
            if (!SessionUtils.validateCaptcha(request, imageCaptcha)) {
                return new AjaxResponse(false, "图片验证码不正确");
            }
            int i = (int) (Math.random() * 1000000 + 100000);
            String messageCode = String.valueOf(i);
            redisService.getValueOps().set(sessionId, messageCode, 2 * 60, TimeUnit.SECONDS);
            logger.info("duan xin is ----------------------" + messageCode);
//            String state = smaClient.sendSMS(mobile, "群商天下验证码:" + messageCode + "");
//            if (state.equals("0")) {
//                return new AjaxResponse(true);
//            } else {
//                return new AjaxResponse(false, "发送失败，请重新发送");
//            }
            return new AjaxResponse(true);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误，请稍后重试");
    }

    /**
     * 保存shop
     *
     * @param request
     * @param response
     * @param mobile
     * @param imageCaptcha
     * @return
     */
    @RequestMapping(value = "addShop", method = RequestMethod.POST)
    public @ResponseBody
    AjaxResponse addShop(HttpServletRequest request, HttpServletResponse response,
            Shop shop) {
        try {
            String sellerId = SessionUtils.getSellerId(request);
            String id = UUID.randomUUID().toString();
            shop.setId(id);
            shop.setSellerId(sellerId);
            Integer a = shopManageService.addShop(shop);
            if (a > 0) {
                return new AjaxResponse(true);
            } else {
                return new AjaxResponse(false, "保存失败");
            }
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return new AjaxResponse(false, "系统错误，请稍后重试");
    }

    //商家管理---审核资料提交
    @RequestMapping(value = "subinfo", method = RequestMethod.GET)
    public ModelAndView subinfo(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("shop/subinfo");
        List<Category> cate = shopManageService.getParentCategory();
        mv.addObject("category", cate);
        return mv;
    }

    //商家管理---审核资料已提交,等待审核
    @RequestMapping(value = "subedinfo", method = RequestMethod.GET)
    public ModelAndView subedinfo(HttpServletRequest request, HttpServletResponse response) {
        ModelAndView mv = new ModelAndView("shop/subedinfo");
        List<Category> cate = shopManageService.getParentCategory();
        mv.addObject("category", cate);
        return mv;
    }
    
    @ResponseBody
    @RequestMapping(value = "captcha", method = RequestMethod.GET, produces = MediaType.IMAGE_PNG_VALUE)
    public byte[] captcha(HttpServletRequest request) throws IOException {
        List<java.awt.Color> textColors = Arrays.asList(new Color(74, 137, 220));
        List<java.awt.Font> textFonts = Arrays.asList(new Font("Courier", Font.PLAIN, 35));
        Captcha captcha = new Captcha.Builder(120, 40)
                .addText(new DefaultTextProducer(),
                        new DefaultWordRenderer(textColors, textFonts))
                .build();
        
        try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
            ImageIO.write(captcha.getImage(), "png", bos);
            request.getSession().setAttribute(Captcha.NAME, captcha);
            return bos.toByteArray();
        }
    }

    //获取省市区
    @RequestMapping(value = "getProvinceList", method = RequestMethod.GET, produces = javax.ws.rs.core.MediaType.APPLICATION_JSON)
    @ResponseBody
    public List<Province> getProvinceList() throws IOException {
        List<Province> plist = userService.getProvince();
        return plist;
    }
    
    @RequestMapping(value = "getCityList", method = RequestMethod.GET, produces = javax.ws.rs.core.MediaType.APPLICATION_JSON)
    @ResponseBody
    public List<City> getCityList(String id) throws IOException {
        List<City> clist = userService.getCity(id);
        return clist;
    }
    
    @RequestMapping(value = "getAreaList", method = RequestMethod.GET, produces = javax.ws.rs.core.MediaType.APPLICATION_JSON)
    @ResponseBody
    public List<Area> getAreaList(String id) throws IOException {
        List<Area> alist = userService.getArea(id);
        return alist;
    }

    //根据大类获取小类list

    @RequestMapping(value = "getCategoryByParent", method = RequestMethod.GET, produces = javax.ws.rs.core.MediaType.APPLICATION_JSON)
    @ResponseBody
    public List<Category> getCategoryByParent(String id) throws IOException {
        List<Category> clist = shopManageService.getCategoryByParent(id);
        return clist;
    }

    //商户管理首页
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView mv = new ModelAndView("dashboard");
//        String sellerId = SessionUtils.getSellerId(request);
//        Shop shop = shopManageService.getShopBySellerId(sellerId);
//        shop.setIdImageUrl(derongVariables.getDomain() + shop.getIdImageUrl());
//        shop.setLicenseUrl(derongVariables.getDomain() + shop.getLicenseUrl());
//        mv.addObject("shop", shop);
        return mv;
    }
    
    
}
